package com.starblink.brand.adapter

import android.content.Context
import android.util.AttributeSet
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentActivity
import com.starblink.android.basic.ext.commContext
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.SubscribeBrandEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.ext.load
import com.starblink.basic.route.RoutePage
import com.starblink.brand.R
import com.starblink.basic.util.CheckUtil
import com.starblink.brand.bean.BrandRightBean
import com.starblink.brand.databinding.CellBrandRightBinding

class BrandRightCardView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleRes: Int = 0
) : ConstraintLayout(context, attrs, defStyleRes) {

    val binding: CellBrandRightBinding = CellBrandRightBinding.inflate(inflater, this, true)
    private val subscribeImg = R.mipmap.icon_brand_followed
    private val unSubscribeImg = R.mipmap.icon_brand_follow
    private lateinit var model: BrandRightBean
    private var searchTerm: String? = null
    private var pageDef : Int? =null
    private var position : Int = 0
    fun bindModel(
        mActivity: FragmentActivity,
        model: BrandRightBean,
        position: Int,
        pageDef:Int,
        searchTerm:String?=null,
    ){
        this.model=model
        this.searchTerm=searchTerm
        this.pageDef=pageDef
        this.position=position
        val brandInfo=model.topBrandInfoVOF
        brandInfo?.let {brandInfo->
            binding.ivBrandBigPic.load(brandInfo.brandImg)
            binding.ivBrandLogo.load(brandInfo.logo, brandInfo.name)
            binding.tvBrandName.text=brandInfo.name
            binding.llDiscount.visibleOrGone(brandInfo.brandDiscount!=null){
                binding.tvBrandDiscount.text="${brandInfo.brandDiscount}%"
            }
            updateSubscribeState()

            binding.ivFollowBtn.run{
                setOnClickListener {
                    //品牌订阅
                    CommonMutateManage.subscribeOrNotBrand(ctx=commContext(),
                        subOrNot = brandInfo.hasSub?:false ,
                        brandId = brandInfo.brandId?:""){hasSub->

                        model.topBrandInfoVOF?.apolloValue("hasSub", hasSub)
                        updateSubscribeState()
                        trackView()
                    }
                }
            }
        }

        setOnClickListener{
            //跳品牌二级页
            navigationTo(RoutePage.Brand.BRAND_DETAIL){
                withString(RoutePage.Brand.ARG_BRAND_ID, "${brandInfo?.brandId}")
                withBoolean(
                    RoutePage.Brand.ARG_IS_DISCOUNT_BRAND,
                    brandInfo?.brandDiscount != null
                )
            }
        }

        initObservable()
        trackView()
    }

    //更新订阅状态
    private fun updateSubscribeState(){
        if(model.topBrandInfoVOF?.hasSub==true){
            binding.ivFollowBtn.setImageResource(subscribeImg)
        }else{
            binding.ivFollowBtn.setImageResource(unSubscribeImg)
        }
    }

    private fun initObservable(){
        FlowBus.with<SubscribeBrandEvent>(FlowConst.SUBSCRIBE_BRAND_EVENT).register(this) {event ->
            if(event.brandId == model.topBrandInfoVOF?.brandId && model.topBrandInfoVOF?.hasSub != event.hasSub){
                model.topBrandInfoVOF?.apolloValue("hasSub", event.hasSub)
                updateSubscribeState()
                trackView()
            }
        }
    }
    fun setCardViewType(itemHeightType:Int = 0){
        if(itemHeightType==0){
            binding.rlBrandItem.layoutParams.height=137.dp2px()
            binding.ivBrandLogo.layoutParams.width=32.dp2px()
            binding.ivBrandLogo.layoutParams.height=32.dp2px()
            binding.tvBrandName.setTextAppearance(commContext(),com.starblink.basic.style.R.style.Guang2_Text_Label_L)
        }else{
            binding.rlBrandItem.layoutParams.height=173.dp2px()
            binding.ivBrandLogo.layoutParams.width=44.dp2px()
            binding.ivBrandLogo.layoutParams.height=44.dp2px()
            binding.tvBrandName.setTextAppearance(commContext(),com.starblink.basic.style.R.style.Guang2_Text_Title1600_M)
        }
    }

    //埋点
    private fun trackView(){
        trackData(
            page = pageDef!!,
            element = SpmElementDef.Element_33014,
            showRatio = 0.1f,
            params = trackMap(position),
            businessSuffixID = businessSuffixId(model)
        )
        binding.ivFollowBtn.trackData(
            page = pageDef!!,
            element = SpmElementDef.Element_33087,
            onlyHit = true,
            traceInfo = model.topBrandInfoVOF?.name,
            params = trackMap(position,ifNeedFollowStatus=false).plus("result" to if (model.topBrandInfoVOF?.hasSub==true) "0" else "1")
        )
    }

    private fun trackMap(position: Int,ifNeedFollowStatus: Boolean = true) = mutableMapOf(
        "index" to (position.toString()),
        "brandName" to (model.topBrandInfoVOF?.name?:"")
    ).apply {
        if(!searchTerm.isNullOrEmpty()){
            //搜索页面的
            //搜索品牌页面使用
            put("searchTerm", searchTerm!!)
            put("searchType", "normal")
            if(ifNeedFollowStatus){
                //搜索页面点击订阅按钮 不要这个状态 想不到吧=====
                put("followStatus", if (model.topBrandInfoVOF?.hasSub == true) "1" else "0")
            }
        }else{
            //其他页面的
            put("followStatus", if (model.topBrandInfoVOF?.hasSub == true) "1" else "0")
        }
    }
}